/**
 * Created by jt on 2017/5/6.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";
import {projGrdSts} from "../config.js";
import gridListTpl from "./grid_list.handlebars";


App.init();
var token = sessionStorage.getItem('token');
var projId = getArgs().id;
var grdTyp = getArgs().sts;

if (token == null || token =='') {
    location.href = HOST_FRT+'/logins/login.html';
}


// 排序
function sortBy (property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}

var GridList = {
    pageNo: 1,
    pageSize: 100,
    // grdRul : '0',
    matDtls: [],        // 物料列表
    exptNams:[],        // 已评标的专家
    exptGrdList:[],     // 专家评标结果汇总
    init: function(){
        this.getGriddingData()
            .then(this.renderGridList)
            .then(this.collectGrdInf)
            .then(this.bindEvent);
    },
    getGriddingData: function() {
        return new Promise((resolve, reject)=>{
            let self = this;
            let data ={
                "projId": projId,
                "grdTyp": grdTyp
            };
            $.ajax({
                url: HOST_ADDR + `/cpmp/bidProjOnMngForPchs/getGrdInf/${self.pageNo}/${self.pageSize}`,
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                data:JSON.stringify(data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        resolve(resp);
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },
    // 渲染列表

    renderGridList: function(resp){
        let self = GridList;
        // 处理数据begin
        $.each(resp.data.list,function(index,item){
            item.projGrdStsFmt = projGrdSts[item.projGrdSts] || '暂无状态';
            item.gridAvailabel = (item.projGrdSts == '02');
        });
        // 处理数据end
        let resultHtml = gridListTpl({gridList: resp.data.list});
        $('.J_grid-list').html(resultHtml);
    },

    // 获取专家评标汇总信息
    collectGrdInf:function(){
        let self = GridList;
        $.ajax({
            url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/collectGrdInf/'+projId,
            type: 'get',
            dataType: 'json',
            headers: {
                'access_token': token,'login_type':'ums'
            },
            contentType: "application/json",
            success: function (resp) {
                if (resp.success) {
                    console.log(resp);
                    if(typeof(resp.data.projInf.grdRul)!='undefined' && resp.data.projInf.grdRul!=null && resp.data.projInf.grdRul!=''){
                        self.grdRul = resp.data.projInf.grdRul;
                    }
                    if(typeof(resp.data.projInf.matDtls)!='undefined' && resp.data.projInf.matDtls!=null && resp.data.projInf.matDtls!=''){
                        self.matDtls = resp.data.matDtls;
                    }
                    self.exptNams = resp.data.exptNams;
                    self.exptGrdList = resp.data.list;
                    self.renderResultList();
                }
                else {
                    alert(resp.msgInf);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    },

    // 展示评标结果汇总信息
    renderResultList:function(){
        let self = GridList;
        if(self.grdRul=='0'){ // 最低单价评标
            self.showLowestPrice();
        }else if(self.grdRul=='2'){ // 最低总价评标
            self.showLowestSumPrice();
        }
    },

    // 最低单价评标
    showLowestPrice:function(){
        let self = GridList;
        var matinfo = self.matDtls;
        var exptNams = self.exptNams;
        var exptGrdList = self.exptGrdList;
        var groupHeaders = [];
        var rows = [];
        var totalLines = 1;  // 总数据行
        var splrIds = [];    // 所有供应商ID
        var subColNames = ['供应商ID','供应商','综合排名'];
        var subColModel = [
            {name:"splrId",index:"splrId",hidden:true},
            {name:"splrNam",index:"splrNam",width:200, sortable:false},
            {name:"allOrd",index:"allOrd",width:70, sortable:false}
        ];
        for(var i=0;i<exptGrdList.length;i++){
            totalLines+=2;
            var matInfo = exptGrdList[i];
            var tmpSplrList = matInfo.grdInfs;
            var tmpLines = [];
            for(var m=0;m<tmpSplrList.length;m++){
                var tmprow = tmpSplrList[m];
                var exptResult = tmpSplrList[m].grdList;
                var sumScore = 0;
                for(var n=0;n<exptResult.length;n++){
                    if(i==0 && m==0){
                        groupHeaders.push({startColumnName:"grdOrd"+n,numberOfColumns:2,titleText:exptNams[n]});
                        subColNames.push('排名');
                        subColNames.push('评标理由');
                        subColModel.push({name:"grdOrd"+n,index:"grdOrd"+n,width:80, sortable:false});
                        subColModel.push({name:"grdRsn"+n,index:"grdRsn"+n,width:180, sortable:false});
                    }
                    tmprow["grdOrd"+n] = exptResult[n].grdOrd;
                    tmprow["grdRsn"+n] = exptResult[n].grdRsn;
                    sumScore+=parseInt(exptResult[n].grdOrd);
                }
                tmprow["sumScore"] = sumScore;
                totalLines += 1;
                tmpLines.push(tmprow);
            }
            tmpLines.sort(sortBy("sumScore"));
            matInfo['lineInfo'] = tmpLines;
            rows.push(matInfo);
        }

        jQuery("#mygrid2").jqGrid({
            width:'100%',
            dataType:'local',
            width:'100%',
            height: 250,
            colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
            colModel:[
                {name:'matId',index:'id', width:50,hidden: true},
                {name:'matCod',index:'matCod', width:80},
                {name:'matNam',index:'matNam', width:150},
                {name:'matUnt',index:'matUnt', width:80,align:"center"},
                {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
                {name:'dlvAdr',index:'dlvAdr', width:80},
                {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
                {name:'memo',index:'memo', width:150}
            ],
            subGrid: true,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            subGridOptions: {
                "plusicon"  : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon"  : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true,
                "selectOnExpand" : true
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id, lastsel;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
                jQuery("#"+subgrid_table_id).jqGrid({
                    datatype: "local",
                    height: '100%',
                    colNames: subColNames,
                    colModel: subColModel,
                    fitColumns: true,
                    shrinkToFit: true,
                    altRows: true
                });
                $("#"+subgrid_table_id).jqGrid('setGroupHeaders', {
                    useColSpanStyle: true,
                    groupHeaders:groupHeaders
                });
                for(var m=0;m<rows[row_id-1].lineInfo.length;m++){
                    var subrowid = m+1;
                    var rowinfo = rows[row_id-1].lineInfo[m];
                    rowinfo.allOrd = m+1;
                    $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                    $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);
                }
            }
        });
        for ( var i = 0; i < rows.length; i++){
            var rowid = i+1;
            rows.matId = matinfo.matId ? matinfo.matId : rowid;
            rows[i].dlvDte = rows[i].dlvDte ? (new Date(rows[i].dlvDte)).Format("yyyy-MM-dd") : '';
            $("#mygrid2").jqGrid('addRowData', rowid, rows[i]);
            $("#mygrid2>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
        }
        $("#mygrid2>tbody>tr.jqgrow").addClass("bg-lightgray");

        function resize(){
            var table_id = "mygrid2";
            var ids = $("#"+table_id).jqGrid("getDataIDs");
            for(var i=0;i<ids.length;i++){
                var subgrid_table_id = table_id+"_"+ids[i]+"_t";
                if($("#"+subgrid_table_id).width()+27<$(".mygrid2").width()){
                    $("#"+subgrid_table_id).jqGrid('setGridWidth', $(".mygrid2").width()-27);
                }
                $("#"+subgrid_table_id).parent().parent().width($("#"+subgrid_table_id).width()+2);
                $("#"+subgrid_table_id).parent().parent().prev().width($("#"+subgrid_table_id).width()+2);
            }
            jQuery("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
            jQuery("#mygrid2").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
        }
        $(window).resize(function(){
            resize();
        });
        resize();
    },

    // 最低总价评标
    showLowestSumPrice:function(){
        let self = GridList;
        var rows = [];
        var groupHeaders = [];
        var exptNams = self.exptNams;
        var exptGrdList = self.exptGrdList;
        var subColNames = ['供应商ID','供应商','综合排名'];
        var subColModel = [
            {name:"splrId",index:"splrId",hidden:true},
            {name:"splrNam",index:"splrNam",width:200, sortable:false,frozen:true},
            {name:"allOrd",index:"allOrd",width:70, sortable:false,frozen:true}
        ];
        for(var i=0;i<exptGrdList.length;i++){
            var rowinfo = exptGrdList[i];
            var sumScore = 0;
            for(var m=0;m<rowinfo.grdInfs.length;m++){
                if(i==0){
                    groupHeaders.push({startColumnName:"grdOrd"+m,numberOfColumns:2,titleText:exptNams[m]});
                    subColNames.push("排名");
                    subColNames.push("评标理由");
                    subColModel.push({name:"grdOrd"+m,index:"grdOrd"+m,width:80, sortable:false});
                    subColModel.push({name:"grdRsn"+m,index:"grdRsn"+m,width:200, sortable:false});
                }
                var resultlist = rowinfo.grdInfs[m];
                rowinfo["grdOrd"+m] = resultlist.grdOrd;
                rowinfo["exptNam"+m] = resultlist.exptNam;
                rowinfo["exptId"+m] = resultlist.exptId;
                rowinfo["grdRsn"+m] = resultlist.grdRsn;
                sumScore += parseInt(resultlist.grdOrd);
            }
            rowinfo["sumScore"] = sumScore;
            rows.push(rowinfo);
        }
        rows.sort(sortBy("sumScore"));
        jQuery("#mygrid2").jqGrid({
            datatype: "local",
            height: '100%',
            colNames: subColNames,
            colModel: subColModel,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true
        });
        $("#mygrid2").jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders:groupHeaders
        });
        for(var m=0;m<rows.length;m++){
            var subrowid = m+1;
            var rowinfo = rows[m];
            rowinfo.allOrd = m+1;
            $("#mygrid2").jqGrid('addRowData', subrowid, rowinfo);
            $("#mygrid2 #"+subrowid).data("rowinfo",rowinfo);
        }
    },


    // 绑定事件
    bindEvent: function(){
        let self = GridList;

        // 修改评标状态 重新评标     2018-01-08  废弃
        $(".reGrid").on("click",function(){
            var grdId = $(this).attr("grdId");
            $.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOnMngForPchs/updateGrdRes/'+grdId,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        alert(resp.msgInf);
                        window.reload();
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });

    },

    // 渲染列表
    renderList(){
        this.getGriddingData()
            .then(this.renderGridList)
            .then(this.bindEvent);
    }
};

App.init();
GridList.init();

jQuery('.logOut').attr('href','../logins/login.html');
